package android.mcsmtms.util;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.mcsmtms.constant.GlobalConstants.Roads;
import android.mcsmtms.constant.GlobalConstants.SituationTypes;
import android.mcsmtms.constant.GlobalConstants.TrafficConditionTypes;
import android.mcsmtms.constant.GlobalProperties;
import android.mcsmtms.domain.MobileUserReport;
import android.mcsmtms.domain.SituationReport;
import android.mcsmtms.domain.SituationSegment;
import android.mcsmtms.domain.User;
import android.os.Handler;
import android.util.Base64;

public class Utilities {

	public static int LOGLEVEL = 1;
	public static boolean WARN = LOGLEVEL > 1;
	public static boolean DEBUG = LOGLEVEL > 0;

	/** The Constant dateFormatString. */
	private final static String dateFormatString = "MM/dd/yyyy hh:mm:ss aaa";
	
	/**
	 * Format default date.
	 *
	 * @param date the date
	 * @return the string
	 */
	public static String formatDefaultDate(Date date) {
		return (new SimpleDateFormat(dateFormatString)).format(date);
	}
	
	public static String encodeBase64UrlSafe(String data) {
		return new String(Base64.encode(data.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
	}
	
	public static void showDefaultAlertDialog(Context ctx,
			DialogInterface.OnClickListener onOkClickListener, String title,
			String message) {
		AlertDialog alertDialog = new AlertDialog.Builder(ctx).create();
		alertDialog.setTitle(title);

		alertDialog.setMessage(message);

		//alertDialog.setButton("OK", onOkClickListener);
		alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", onOkClickListener);

		alertDialog.show();
	}

	public static AlertDialog showDefaultAlertDialog(Context ctx,
			DialogInterface.OnClickListener onOkClickListener,
			DialogInterface.OnClickListener onCancelClickListener,
			String title, String message) {

		AlertDialog alertDialog = new AlertDialog.Builder(ctx).create();
		alertDialog.setTitle(title);

		alertDialog.setMessage(message);
		alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", onOkClickListener);
		alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", onCancelClickListener);
		alertDialog.setCancelable(true);
		alertDialog.show();
		return alertDialog;
	}

	public static AlertDialog showTimedAlertDialog(Context ctx,
			DialogInterface.OnClickListener onOkClickListener,
			DialogInterface.OnClickListener onCancelClickListener,
			String title, String message) {
		AlertDialog alertDialog = new AlertDialog.Builder(ctx).create();
		alertDialog.setTitle(title);

		alertDialog.setMessage(message);
		alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", onOkClickListener);
		alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", onCancelClickListener);
		alertDialog.setCancelable(true);

		alertDialog.show();

		return alertDialog;
	}

	public static void showDefaultAlertDialog(Context ctx, String title,String message) {
		DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				// do nothing
				dialog.dismiss();
			}
		};
		showDefaultAlertDialog(ctx, onClickListener, title, message);
	}

	public static void showDefaultAlertDialog(Context ctx, String title,
			String message, final Handler enableGpsHandler) {
		DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				dialog.dismiss();
				enableGpsHandler.sendEmptyMessage(0);
			}
		};
		showDefaultAlertDialog(ctx, onClickListener, title, message);
	}

//	public static void openOptions(Activity ctx) {
//		Intent openOptionsIntent = new Intent(ctx, Options.class);
//		ctx.startActivity(openOptionsIntent);
//	}

	public static class StringUtils {
		public static boolean isNullOrEmpty(String str) {
			return (str == null || "".equals(str));
		}
	}
	
	public static User getLoggedUser(Activity activity) {
		//((GlobalProperties) activity.getApplication())
		return ((GlobalProperties) activity.getApplication()).getLoggedUser();
	}
	
	public static void setLoggedUser(Activity activity, User user) {
		((GlobalProperties) activity.getApplication()).setLoggedUser(user);
	}
	
	public static String getErrorMessage(Exception ex) {
		if(ex != null && ex.getMessage() != null && !ex.getMessage().isEmpty())
			return ex.getMessage();
		return "Blank error message.";
	}
	
	public static String generateSituationDetails(SituationReport situationReport) {
		if(situationReport == null) return "";
		
		String alertMessage = "";
		
		String situationDetails = "";
		
		try {
			for(SituationSegment segment : situationReport.getSituationSegmentList()) {
				situationDetails += segment.getSituationDesc() + 
									"(" + segment.getTrafficConditionDesc()  + "),\n";
			}
			if((situationDetails.length() - 2) >= 0)
				situationDetails = situationDetails.substring(0, situationDetails.length() - 2);
			
			alertMessage += situationDetails + " reported at " + 
								situationReport.getRoadDesc() + " " +
								situationReport.getLastUpdateDateTimeString()
								+ "\nby " + situationReport.getUser().getFullName();
		} catch (Exception ex) {
			ex.printStackTrace();
			alertMessage = "";
		}
		
		return alertMessage;
	} 
	
	public static String generateSegmentDetails(SituationReport report, SituationSegment segment) {
		if(segment == null) return "";
		
		String segmentDetails = "";
		
		try {
			
			segmentDetails += segment.getSituationDesc() + 
								"(" + segment.getTrafficConditionDesc()  + ")\n";
			
			segmentDetails += " reported at " + 
								report.getRoadDesc() + " " + report.getLastUpdateDateTimeString()
								+ "\nby " + report.getUser().getFullName();
		} catch (Exception ex) {
			ex.printStackTrace();
			segmentDetails = "";
		}
		
		return segmentDetails;
	}
	
	public static String generateMobileUserReportDetails(MobileUserReport mobileUserReport) {
		if(mobileUserReport == null) return "";
		
		String mobileUserReportDetails = "";
		
		try {
			
			mobileUserReportDetails += mobileUserReport.getSituationDesc() + 
								"(" + mobileUserReport.getTrafficConditionDesc()  + ")\n";
			
			mobileUserReportDetails += " reported at " + 
								mobileUserReport.getRoadDesc() + " " + mobileUserReport.getReportDateTimeString() 
								+ "\nby " + mobileUserReport.getUser().getFullName();
		} catch (Exception ex) {
			ex.printStackTrace();
			mobileUserReportDetails = "";
		}
		
		return mobileUserReportDetails;
	}

//	public static class GPSUtils {
//		public static GeoPoint getPoint(double lat, double lon) {
//			return (new GeoPoint((int) (lat * 1000000.0),
//					(int) (lon * 1000000.0)));
//		}
//	}
	
//	public static class MapUtils {
//		/**
//		 * Does the actual drawing of the route, based on the geo points
//		 * provided in the nav set
//		 * 
//		 * @param navSet
//		 *            Navigation set bean that holds the route information,
//		 *            incl. geo pos
//		 * @param color
//		 *            Color in which to draw the lines
//		 * @param mapView
//		 *            Map view to draw onto
//		 */
//		public static void drawPath(NavigationDataSet navSet, int color, MapView mapView) {
//
//			// Log.d(myapp.APP, "map color before: " + color);
//
//			// color correction for dining, make it darker
//			if (color == Color.parseColor("#add331"))
//				color = Color.parseColor("#6C8715");
//			// Log.d(myapp.APP, "map color after: " + color);
//
//			// Collection overlaysToAddAgain = new ArrayList();
//			// for (Iterator iter = mMapView01.getOverlays().iterator(); iter
//			// .hasNext();) {
//			// Object o = iter.next();
//			// //Log.d(myapp.APP, "overlay type: " + o.getClass().getName());
//			// if (!RouteOverlay.class.getName()
//			// .equals(o.getClass().getName())) {
//			// // mMapView01.getOverlays().remove(o);
//			// overlaysToAddAgain.add(o);
//			// }
//			// }
//			// //mMapView01.getOverlays().clear();
//			// mMapView01.getOverlays().addAll(overlaysToAddAgain);
//
//			for (Placemark placemark : navSet.getPlacemarks()) {
//				if(placemark==null) continue;
//				
//				String path = placemark.getCoordinates();
//				// Log.d(myapp.APP, "path=" + path);
//				if (path != null && path.trim().length() > 0) {
//					String[] pairs = path.trim().split(" ");
//
//					// Log.d(myapp.APP, "pairs.length=" + pairs.length);
//
//					String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude
//															// lngLat[1]=latitude
//															// lngLat[2]=height
//
//					// Log.d(myapp.APP, "lnglat =" + lngLat + ", length: "
//					// + lngLat.length);
//
//					if (lngLat.length < 3)
//						lngLat = pairs[1].split(","); // if first pair is not
//														// transferred
//														// completely,
//														// take seconds pair
//														// //TODO
//
//					try {
//						GeoPoint startGP = new GeoPoint(
//								(int) (Double.parseDouble(lngLat[1]) * 1E6),
//								(int) (Double.parseDouble(lngLat[0]) * 1E6));
//						mapView.getOverlays().add(
//								new RouteOverlay(startGP, startGP, 1));
//						GeoPoint gp1;
//						GeoPoint gp2 = startGP;
//
//						for (int i = 1; i < pairs.length; i++) // the last one
//																// would
//																// be crash
//						{
//							lngLat = pairs[i].split(",");
//
//							gp1 = gp2;
//
//							if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0
//									&& gp1.getLongitudeE6() > 0
//									&& gp2.getLatitudeE6() > 0
//									&& gp2.getLongitudeE6() > 0) {
//
//								// for GeoPoint, first:latitude,
//								// second:longitude
//								gp2 = new GeoPoint(
//										(int) (Double.parseDouble(lngLat[1]) * 1E6),
//										(int) (Double.parseDouble(lngLat[0]) * 1E6));
//
//								if (gp2.getLatitudeE6() != 22200000) {
//									mapView.getOverlays()
//											.add(new RouteOverlay(gp1, gp2, 2,
//													color));
//									// Log.d(myapp.APP,
//									// "draw:" + gp1.getLatitudeE6() + "/"
//									// + gp1.getLongitudeE6() + " TO "
//									// + gp2.getLatitudeE6() + "/"
//									// + gp2.getLongitudeE6());
//								}
//							}
//							// Log.d(myapp.APP,"pair:" + pairs[i]);
//						}
//						// routeOverlays.add(new RouteOverlay(gp2,gp2, 3));
//						mapView.getOverlays().add(new RouteOverlay(gp2, gp2, 3));
//					} catch (NumberFormatException e) {
//						Log.e(MapUtils.class.getName(), "Cannot draw route.", e);
//						
//						e.printStackTrace();
//					}
//				}
//			}
//
//			// mMapView01.getOverlays().addAll(routeOverlays); // use the
//			// default color
//			mapView.setEnabled(true);
//		}
//
//	}
}
